package com.guanyong.admin.controllers.api;

import com.guanyong.admin.handle.TokenHelper;
import com.guanyong.model.UserBaseModel;
import com.guanyong.model.UserLoginLogModel;
import com.guanyong.services.UserBaseService;
import com.guanyong.services.UserLoginLogService;
import com.guanyong.utils.Cache.ICahce.ICache;
import com.guanyong.utils.Comm.ResultCode;
import com.guanyong.utils.Comm.ResultObject;
import com.guanyong.utils.LogHelper.LogHelper;
import com.guanyong.utils.NetUtils.CookieUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by mxk on 2017/6/5.
 */

@RestController
@RequestMapping("/api/")
public class UserLoginApi {

    @Autowired
    TokenHelper tokenHelper;
    @Autowired
    ICache cache;
    @Autowired
    UserBaseService userBaseService;

    @Autowired
    UserLoginLogService userLoginLogService;

    @Value("${mortise.VerifyCode.cache.codekey}")
    String mortisecacheVerfiCode;
    @Value("${mortise.usercas.cookie.loginName}")
    String mortiseloginName;

    /**
     * 用户信息写入cookie
     * @param rememberMe 是否记住登录帐号
     * @param loginName 登录账号
     * @param user 登录或注册之后的用户对象
     * @param reponse
     * @param request
     * @return
     */
    ResultObject<Boolean> writeUserCookie(boolean rememberMe,
                                          String loginName,
                                          UserBaseModel user,
                                          HttpServletResponse reponse,
                                          HttpServletRequest request){
        ResultObject<Boolean> resultObject=new ResultObject<Boolean>();        //是否记住用户名
        if(rememberMe) {
            CookieUtils.addCookie(reponse, mortiseloginName, loginName, 0, "", "");
        }else {
            CookieUtils.delCookie(request,reponse, mortiseloginName);
        }
        //生成令牌信息，每次访问鉴别身份
        tokenHelper.setCasToken(user.getfId(),user.getfPassword(),reponse,request);
        return resultObject;
    }

    @RequestMapping(value="login", method= RequestMethod.POST)
    public ResultObject<UserBaseModel> UserAdminLogin(
            @RequestParam String uid,
            @RequestParam String pwd,
            @RequestParam String valcode,
            @RequestParam String valcodekey,
            @RequestParam boolean remember,
            HttpServletRequest request, HttpServletResponse reponse ) {

        Object CacheValCode = cache.get(mortisecacheVerfiCode,valcodekey);
        ResultObject<UserBaseModel> result = null;
        //判断验证码
        if (CacheValCode!=null&&String.valueOf(CacheValCode).equalsIgnoreCase(valcode)) {
            try {
                String ip=com.guanyong.utils.NetUtils.IPUtil.getIpAddr(request);
                //登录验证
                result = userBaseService.UserLogin(uid, pwd,2,ip,1);
                //登录验证通过
                if (result.getCode().equals(ResultCode.LoginSucess)) {
                    //写如cookie
                    writeUserCookie(remember,uid,result.getResult(),reponse,request);

                }
                //登录验证失败
                else {
                    LogHelper.logger().info("登录验证失败：登录账号：" + uid + "，登录密码：" + pwd + "，失败原因：" + result.getCode().toString());
                    result = new ResultObject<UserBaseModel>();
                    //所有验证失败的情况都返回密码错误，防止恶意猜测密码
                    result.setCode(ResultCode.LoginPassError);
                }
            } catch (Exception ex) {//登录验证发生异常

                if (result == null) {
                    result = new ResultObject<UserBaseModel>();
                    result.setCode(ResultCode.ServiceError);
                }
                LogHelper.logger().error(ex.getMessage());
            }
        } else {
            //
            result = new ResultObject<UserBaseModel>();
            //失败结果-验证码验证失败
            result.setCode(ResultCode.CehckCodeError);
        }

        return result;
    }
}
